package com.uiotsoft.util.str;

import java.io.UnsupportedEncodingException;


public class StringUtil {
	//��ʮ������ת�����ֽ�����
	public static byte[] hexStringToByte(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		// toUpperCase���ַ����е������ַ�ת��Ϊ��д
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		// toCharArray�����ַ���ת��Ϊһ���µ��ַ����顣
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	// charToByte������ָ���ַ��ĵ�һ���������ַ����е�������������ƥ���ַ�
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	public static short bytes2Short2(byte[] b) {
		short i = (short) (((b[1] & 0xff) << 8) | b[0] & 0xff);
		return i;
	}

	// ���ֽ�����ת��Ϊ16�����ַ���
	public static String BinaryToHexString(byte[] bytes) {
		String hexStr = "0123456789ABCDEF";
		String result = "";
		String hex = "";
		for (byte b : bytes) {
			hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
			hex += String.valueOf(hexStr.charAt(b & 0x0F));
			result += hex;
		}
		return result;
	}

	//��16����ת�����ַ���
	public static String hexStringToString(String hexStr) {
		if(hexStr == null||hexStr.equals("")) {
			return null;
		}
		hexStr = hexStr.replaceAll(" ", "");
		String str = "0123456789ABCDEF";
		char[] hexs = hexStr.toCharArray();
		byte[] keyword = new byte[hexStr.length()/2];
		int n;

		for (int i = 0; i < keyword.length; i++) {
			n = str.indexOf(hexs[2*i])*16;
			n += str.indexOf(hexs[2*i+1]);
			keyword[i]=(byte) (0xff&n);
		}

		try {
			return new String(keyword,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "编码异常";
		}
	}

	//���ַ���ת����16����
	public static String stringToHexString(String str) {
	    char[] chars = "0123456789ABCDEF".toCharArray();
	    StringBuilder sb = new StringBuilder("");
	    byte[] bs = str.getBytes();
	    int bit;
	    for (int i = 0; i < bs.length; i++) {
	        bit = (bs[i] & 0x0f0) >> 4;
	        sb.append(chars[bit]);
	        bit = bs[i] & 0x0f;
	        sb.append(chars[bit]);
	    }
	    return sb.toString().trim();
	}

	public static String BinaryToString(byte[] bytes) {
		String hexString = StringUtil.BinaryToHexString(bytes);
		hexString = hexString.replaceAll(" ", "");
		String str = StringUtil.hexStringToString(hexString);
		return str;
	}

	public static byte[] StringToBinary(String str) {
		String hexString = StringUtil.stringToHexString(str);
		byte[] bytes = StringUtil.hexStringToByte(hexString);
		return bytes;
	}

}
